package com.module.third.qq

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.lifecycle.*
import com.module.frame.app.AppManager
import com.module.frame.base.BaseVmVdbActivity
import com.module.frame.ext.observe
import com.module.frame.ext.postEvent
import com.module.third.ext.qqLoginSharedFlow
import com.module.third.qq.model.QQViewModel
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import kotlinx.coroutines.CoroutineScope
import org.json.JSONException
import org.json.JSONObject

class QQUtils(scope: CoroutineScope, lifecycle: Lifecycle) : ViewModelStoreOwner {

    //直接去生命周期的作用域
    constructor(lifecycle: Lifecycle) : this(
        lifecycle.coroutineScope,
        lifecycle
    )

    private var QQ_APP_ID = ""
    private var mTencent: Tencent? = null
    private var data: JSONObject? = null
    private val mViewModel: QQViewModel by lazy {
        ViewModelProvider(this).get(QQViewModel::class.java)
    }

    private val mViewModelStore by lazy {////定义ViewModelStore变量
        ViewModelStore()
    }


    private val activity by lazy {
        AppManager.getInstance().currentActivity()
    }

    init {
        observe(scope, lifecycle, mViewModel.failFlow) {
            Toast.makeText(activity, it, Toast.LENGTH_SHORT).show()
            hideLoading()
        }
        observe(scope, lifecycle, mViewModel.qqIdFlow) {
            QQ_APP_ID = it
            login()
        }
        observe(scope, lifecycle, mViewModel.infoFlow) {
            it.openid = getOpenId()
            postEvent(qqLoginSharedFlow, it)
        }
        /**
         * 加载框监听
         */
        observe(scope, lifecycle, mViewModel.loadDialogShareFlow) {
            if (it) {
                showLoading()
            } else {
                hideLoading()
            }
        }
        lifecycle.addObserver(object : DefaultLifecycleObserver{
            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                destroy()
            }
        })
    }

    /**
     * QQ监听
     */
    private val qqListener: MyQQListener = object : MyQQListener() {
        override fun onComplete(o: Any) {
            hideLoading()
            try {
                val jsonObject = o as JSONObject
                setData(jsonObject)
                getQQInfo()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        override fun onError(uiError: UiError) {
            hideLoading()
        }

        override fun onCancel() {
            hideLoading()
        }
    }

    fun login() {
        showLoading()
        if (QQ_APP_ID.isNullOrEmpty()) {
            mViewModel.getQQAppId()
        } else {
            mTencent = Tencent.createInstance(QQ_APP_ID, activity)
            if (mTencent == null) {
                return
            }
            mTencent?.let {
                //Session无效了，则重新登录
                if (!it?.isSessionValid) {
                    it?.login(activity, "all", qqListener)
                }
            }

        }
    }

    fun getQQInfo() {
        mViewModel.getQQInfo(
            getAccessToken(), QQ_APP_ID,
            getOpenId()
        )
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (mTencent == null) {
            return
        }
        Tencent.onActivityResultData(requestCode, resultCode, data, qqListener)
    }

    fun setData(data: JSONObject?) {
        this.data = data
    }

    private fun getAccessToken(): String? {
        var token: String? = null
        if (data == null) {
            return token
        }
        try {
            token = data?.getString("access_token")
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return token
    }

    private fun getOpenId(): String? {
        var openid: String? = null
        if (data == null) {
            return openid
        }
        try {
            openid = data?.getString("openid")
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return openid
    }


    private fun showLoading() {
        if (activity is BaseVmVdbActivity<*, *>) {
            (activity as BaseVmVdbActivity<*, *>).showLoading()
        }
    }

    private fun hideLoading() {
        if (activity is BaseVmVdbActivity<*, *>) {
            (activity as BaseVmVdbActivity<*, *>).hideLoading()
        }
    }

    //跳转QQ
    fun jumpQQ(context: Context) {
        try {
            val lan = context.packageManager.getLaunchIntentForPackage("com.tencent.mobileqq")
            val intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.component = lan!!.component
            context.startActivity(intent)
        } catch (e: Exception) {
            jumpQQ(context)
        }
    }

    //跳转QQ好友
    fun jumpQQFriend(context: Context?, qq: String?) {
        try {
            context?.startActivity(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse(String.format("mqqwpa://im/chat?chat_type=wpa&uin=%s", qq))
                )
            )
        } catch (e: Exception) {
            Toast.makeText(context, "您还没有安装QQ，请先安装软件", Toast.LENGTH_SHORT).show()
        }
    }
    //跳转QQ群

    //跳转QQ群
    /****************
     *
     * 发起添加群流程。群号：私人空间交流群(813085344) 的 key 为： f0wDhes5UWWQrUyKj4piIpyYPIDjnqht
     * 调用 joinQQGroup(f0wDhes5UWWQrUyKj4piIpyYPIDjnqht) 即可发起手Q客户端申请加群 私人空间交流群(813085344)
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回false表示呼起失败
     */
    fun jumpQQGroup(context: Context?, key: String): Boolean {
        val intent = Intent()
        intent.data =
            Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D$key")
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        return try {
            context?.startActivity(intent)
            true
        } catch (e: Exception) {
            // 未安装手Q或安装的版本不支持
            false
        }
    }

    fun destroy() {
        viewModelStore.clear()
    }

    override fun getViewModelStore(): ViewModelStore {
        return mViewModelStore
    }

}